package org.huangrui.javase.thread.Interrupt;

/**
 * @Author hr
 * @Create 2025-11-08 15:01
 **/
public class T02SafeStop {
    private static volatile boolean isRunning = true;

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(){
            @Override
            public void run() {
                while (isRunning) {
                    try {
                        // 模拟耗时操作
                        Thread.sleep(1000);
                        System.out.println("Worker thread is running");
                    } catch (InterruptedException e) {
                        System.out.println("Worker thread is interrupted");
                        break;
                    }
                }
                // 进行必要的清理工作
                System.out.println("Cleaning up resources...");
                //结束线程
                System.out.println("Worker thread is exiting");
            }
        };
        worker.start();

        // 主线程等待一段时间后请求终止工作线程
        Thread.sleep(5000);
        isRunning = false;
    }
}
